import {
  Body,
  ClassSerializerInterceptor,
  Controller,
  Get,
  Post,
  Req,
  UseGuards,
  UseInterceptors,
} from '@nestjs/common';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import { AuthGuard } from '@nestjs/passport';
import { LoginDto } from './dto/login.dto';
import { LocalStorage } from './strategy/local.strategy';
import { AuthService } from './auth.service';
import { RegisterDto } from './dto/register.dto';
import { generateRandomName } from '@/utils/randomNickName';
import { JwtAuthGuard } from '@/auth/guard/jwt-auth.guard';
import { CurrentUser } from '@/decorators/current-user.decorator';

@ApiTags('注册登陆')
@Controller('auth')
export class AuthController {
  constructor(
    private localStorage: LocalStorage,
    private readonly authService: AuthService,
  ) {}

  //注册
  @ApiOperation({ summary: '注册' })
  @UseInterceptors(ClassSerializerInterceptor)
  @Post('register')
  async register(@Body() registerUser: RegisterDto) {
    const { nickname, email } = registerUser;
    if (!nickname) {
      registerUser.nickname = generateRandomName();
    }
    if (!email) {
      registerUser.email = '123@example.com';
    }
    return Object.assign(await this.authService.register(registerUser), {
      message: '注册成功',
    });
  }

  //登录
  @ApiOperation({ summary: '登录' })
  @UseInterceptors(ClassSerializerInterceptor)
  @Post('login')
  async login(@Body() loginUser: LoginDto) {
    //校验用户
    const result = await this.localStorage.validate(
      loginUser.username,
      loginUser.password,
    );
    const loginObj = {
      user_id: result.user_id,
      username: result.username,
      role: result.role,
    };
    //生成token
    return Object.assign(await this.authService.login(loginObj), {
      message: '登录成功',
    });
  }

  //获取用户信息
  @ApiOperation({ summary: '获取用户信息' })
  @UseGuards(JwtAuthGuard)
  @Get('user-info')
  async getUserInfo(@CurrentUser() currentUser) {
    const result = {
      user_id: currentUser.user_id,
      nickname: currentUser.nickname,
      avatar: currentUser.avatar_url,
      role: currentUser.role,
    };
    return result;
  }
}
